package com.example.demo.resource;

import com.example.demo.bean.CheckCode;
import com.example.demo.service.OneKeyCommentService;
import com.example.demo.service.impl.OneKeyCommentServiceImpl;
import com.example.demo.utils.JWLoginUtil;
import org.springframework.web.bind.annotation.RequestBody;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;

@Path("comments")
public class OneKeyCommentResource {
    private OneKeyCommentService service = new OneKeyCommentServiceImpl();

    private static Random random = new Random();

    @Path("code")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public CheckCode getCode(){

        CheckCode checkCode = new CheckCode();

        try {
            checkCode = JWLoginUtil.getCheckCode("code-"+String.valueOf(1000000+random.nextInt(8999999))+".png");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return checkCode;
    }


    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Map<String, Object> login(@RequestBody Map<String,Object> map){

        Map<String, Object> result = new LinkedHashMap<>();

        String id = map.get("user").toString();
        String pwd = map.get("pwd").toString();
        String code = map.get("code").toString();
        String cookie = map.get("cookie").toString();


        int  loginResult  = service.loginJw(id, pwd, code,cookie);

        if (loginResult == 1) {
            ArrayList<String[]> list = null;
            int num = 0;
            try {
                list = service.getNeedCommentList();
                num = service.oneKeyComment(list);

                ArrayList<String> rslList = new ArrayList();
                for (String[] s : list) {
                    rslList.add(s[1]);
                }
                result.put("state", "ok");
                result.put("needCmt", rslList);
                result.put("cmtSuccessNum", rslList.size());
                result.put("code", 1);
            } catch (Exception e) {
                e.printStackTrace();
                result.put("state", "failed");
                result.put("msg", "评教时出错，请联系管理员");
                result.put("code", -6);
            }

        }else{
            result.put("state", "failed");
            result.put("msg", "登录失败");
            result.put("code", loginResult);
        }
        return result;
    }
}
